package net.wicp.tams.common.others;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import org.apache.commons.lang3.Validate;

import com.aliyuncs.IAcsClient;
import com.aliyuncs.rds.model.v20140815.DescribeBinlogFilesRequest;
import com.aliyuncs.rds.model.v20140815.DescribeBinlogFilesResponse;
import com.aliyuncs.rds.model.v20140815.DescribeBinlogFilesResponse.BinLogFile;
import com.aliyuncs.rds.model.v20140815.DescribeDBInstanceHAConfigRequest;
import com.aliyuncs.rds.model.v20140815.DescribeDBInstanceHAConfigResponse;
import com.aliyuncs.rds.model.v20140815.DescribeDBInstanceHAConfigResponse.NodeInfo;
import com.aliyuncs.rds.model.v20140815.DescribeDBInstancesRequest;
import com.aliyuncs.rds.model.v20140815.DescribeDBInstancesResponse;
import com.aliyuncs.rds.model.v20140815.DescribeDBInstancesResponse.DBInstance;

import lombok.extern.slf4j.Slf4j;
import net.wicp.tams.common.http.download.Download;
import net.wicp.tams.common.others.util.AcsClientCreator;
import net.wicp.tams.commons.constant.DateFormatCase;
import net.wicp.tams.commons.thread.threadlocal.ObjectCreator;
import net.wicp.tams.commons.thread.threadlocal.PerthreadManager;

@Slf4j
public class RdsUtil {
	public static List<String> findDBInstanceIds() {
		DescribeDBInstancesRequest describe = new DescribeDBInstancesRequest();
		ObjectCreator<IAcsClient> creator = PerthreadManager.getInstance().createValue("aliyun-java-sdk-rds",
				new AcsClientCreator());
		IAcsClient client = creator.createObject();
		try {
			DescribeDBInstancesResponse response = client.getAcsResponse(describe);
			List<DBInstance> items = response.getItems();
			List<String> retlist = new ArrayList<>();
			for (DBInstance dbInstance : items) {
				retlist.add(dbInstance.getDBInstanceId());
			}
			return retlist;
		} catch (Exception e) {
			log.error("创建DBInstancesResponse时失败", e);
			throw new IllegalAccessError(e.getMessage());
		}
	}

	public static List<NodeInfo> findNodeInfos(String dbInstanceId) {
		DescribeDBInstanceHAConfigRequest request = new DescribeDBInstanceHAConfigRequest();
		request.setDBInstanceId(dbInstanceId);// rdsuueafyuqbzfu
		ObjectCreator<IAcsClient> creator = PerthreadManager.getInstance().createValue("aliyun-java-sdk-rds",
				new AcsClientCreator());
		IAcsClient client = creator.createObject();
		try {
			DescribeDBInstanceHAConfigResponse response = client.getAcsResponse(request);
			List<NodeInfo> items = response.getHostInstanceInfos();
			return items;
		} catch (Exception e) {
			log.error("查询节点失败", e);
			throw new IllegalAccessError(e.getMessage());
		}
	}

	public static List<BinLogFile> findBinLogFiles(String dbInstanceId, Date startTime, Date endTime) {
		Validate.notNull(dbInstanceId, "db实例ID不能为空");
		Validate.notNull(startTime, "开始时间不能为空");
		Validate.notNull(endTime, "结束时间不能为空");
		DescribeBinlogFilesRequest request = new DescribeBinlogFilesRequest();
		request.setDBInstanceId(dbInstanceId);// rdsuueafyuqbzfu
		request.setStartTime(DateFormatCase.TZyyyyMMddHHmmss.getInstanc().format(startTime));
		request.setEndTime(DateFormatCase.TZyyyyMMddHHmmss.getInstanc().format(endTime));
		ObjectCreator<IAcsClient> creator = PerthreadManager.getInstance().createValue("aliyun-java-sdk-rds",
				new AcsClientCreator());
		IAcsClient client = creator.createObject();
		DescribeBinlogFilesResponse resp;
		try {
			resp = client.getAcsResponse(request);
			List<BinLogFile> binlogs = resp.getItems();
			return binlogs;
		} catch (Exception e) {
			log.error("请求binlog日志失败", e);
			throw new IllegalAccessError(e.getMessage());
		}
	}

	public static List<BinLogFile> findBinLogFilesMax(final String dbInstanceId, final String hostInstanceId,
			Date startTime, Date endTime) {
		List<BinLogFile> retlist = findBinLogFiles(dbInstanceId, startTime, endTime);
		CollectionUtils.filter(retlist, new Predicate() {
			@Override
			public boolean evaluate(Object object) {
				BinLogFile temp = (BinLogFile) object;
				return hostInstanceId.equals(temp.getHostInstanceID());
			}
		});
		return retlist;
	}

	/***
	 * 下载binLogFile文件
	 * 
	 * @param binLogFile
	 *            binLogFile文件信息
	 * @param dirPath
	 *            下载文件的存放路径
	 * @return 下载的文件路径
	 * @throws IOException
	 */
	public static String downloadBinLogFiles(BinLogFile binLogFile, String dirPath) throws IOException {
		return downloadBinLogFiles(binLogFile, new File(dirPath));
	}

	/**
	 * 下载binLogFile文件
	 * 
	 * @param binLogFile
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public static String downloadBinLogFiles(BinLogFile binLogFile, File file) throws IOException {
		if (file == null) {
			return "";
		}
		if (!file.exists()) {
			file.mkdir();
		}
		Download download = new Download(binLogFile.getDownloadLink(), binLogFile.getFileSize(), file.getPath(), null);
		String retpath = download.download();
		return retpath;
	}
}
